1.后端代码概览

// /login登录接口
router.post('/login', function(req, res, next) {
  const {userName, password} = req.body
  if (userName) {
    const userInfo = password ? getPasswordByName(userName) : ''
    if (!userInfo || !pawwsord || userInfo.password !== password) {
      res.status(401).send({
        code: 401,
        mes: 'user name or password is wrong',
        data: {}
      })
    } else {
      res.send({
        code: 200,
        mes: 'success',
        data: {
          token: jwt.sign({ name: userName }, 'abcd', {
            expiresIn: 60
          })
        }
      })
    }
  } else {
    res.status(401).send({
      code: 401,
      mes: 'user name is empty',
      data: {}
    })
  }
})

// 接口拦截
const whiteListUrl = {
  get: {},
  post: {
    '/index/login'
  }
}

const hasOneOf = {str, arr} => {
  return arr.some(item => item.includes(str))
}

app.all('*', (req, res, next) => {
  let method = req.method.tolowerCase()
  let path = req.path
  if (whiteListUrl[method] && hasOneOf(path, whiteListUrl[methods])).next()
  else {
    const token = req.headers.authorization
    if (!token) res.status(401).send('there is no token, please login')
    else {
      jwt.verify(token, 'abcd', (error, decode) => {
        if (error) res.send({
          code: 401,
          mes: 'token error',
          data: {}
        }) else {
          req.userName = decode.name
          next()
        }
      })
    }
  }
})

2.登录以及Token处理

(1)路由守卫判断有没有token,没有的话进入login页
(2)如果有的话,重新请求服务器获取token,放入cookies,进入页面
(3)login登录成功后,返回token放入cookies
(4)每次请求的时候headers里加入token验证

3.Token过期处理

后端代码:

 token: jwt.sign({ name: userName }, 'abcd', {
        expiresIn: 60
      })

token设置为60秒过期,每次请求

4.退出登录

跳转页面,清除token


岳_轻风
39 声望17 粉丝